package com.cac.demo.service.wmsDeliveryCoordinate;

import com.alibaba.fastjson.JSONObject;
import com.cac.demo.dao.wmsDeliveryCoordinate.WmsDeliveryCoordinateDao;
import com.cac.demo.entity.materialScan.WmsDeliverPlanDTO;
import com.cac.demo.service.cemopHandoverForm.CemopDeliverPlanService;
import com.cac.demo.service.gkinterface.WorkService;
import com.cac.demo.util.CreatMsgId;
import com.cac.demo.util.DateUtil;
import com.cac.demo.util.adapter.DaoException;
import com.cac.demo.util.adapter.QueryReqBean;
import com.cac.demo.util.adapter.QueryRespBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class WmsDeliveryCoordinateService {

    @Autowired
    private WmsDeliveryCoordinateDao wmsDeliveryCoordinateDao;
    @Autowired
    private Environment environment;
    @Autowired
    private WorkService workService;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private CemopDeliverPlanService cemopDeliverPlanService;

    //删除协调单
    @Transactional
    public int deleteDtoById(String id) {
        if (StringUtil.isEmpty(id)) {
            throw new DaoException("删除失败，参数为null");
        }
        try {
            int count =wmsDeliveryCoordinateDao.deleteDtoId(id);
            return count;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }
    //创建协调单
    @Transactional
    public int insertWmsDeliveryCo(HashMap hashMap) {
        return wmsDeliveryCoordinateDao.insertWmsDelCoordinate(hashMap);

    }
    //查询该条码是否有协调单
    public int searchIsCoordinate(HashMap map){
        return wmsDeliveryCoordinateDao.searchIsCoordinate(map);
    }

    public int queryIsNoInvDelivery(HashMap map){
        return wmsDeliveryCoordinateDao.queryIsNoInvDelivery(map);
    }
    public int searchIsBzj(HashMap map){
        return wmsDeliveryCoordinateDao.searchIsBzj(map);
    }

    //协调单查询
    public QueryRespBean<List<HashMap>> searchWmsDelCoordinate(QueryReqBean<HashMap> queryReqBean, Date startTime, Date endTime) {
        QueryRespBean<List<HashMap>> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            HashMap searchParams = queryReqBean.getSearchParams();
            Page<List<HashMap>> dataList = wmsDeliveryCoordinateDao.searchWmsDelCoordinate(searchParams, startTime, endTime);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //提交归零申请
    @Transactional
    public int updateWmsDeliveryCo(Map map) {
        String wmsDeliveryCoordinateId = (String) map.get("wmsDeliveryCoordinateId");
        if (wmsDeliveryCoordinateId == null || wmsDeliveryCoordinateId.equals("")) {
            return 0;
        } else {
            Integer result = wmsDeliveryCoordinateDao.searchStatus(wmsDeliveryCoordinateId);
            if (result == 0) {
                return wmsDeliveryCoordinateDao.updateWmsDeliveryCo(map);
            } else return 0;
        }
    }
    public String getSystem(Map map) {
        String wmsDeliveryCoordinateId = (String) map.get("wmsDeliveryCoordinateId");
        if (wmsDeliveryCoordinateId == null || wmsDeliveryCoordinateId.equals("")) {
            return "";
        } else {
            return cemopDeliverPlanService.getSystemByCoordinateId(wmsDeliveryCoordinateId);
        }
    };

    //归零
    public String updateToZeroWmsDeliveryCo(Map map, List<HashMap> list) {
        int success=0,error=0;
        String msg="";
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        try{
            for(HashMap coor : list){
                coor.put("endCode", map.get("applyEmpcode"));
                coor.put("lastUpdateBy", map.get("applyEmpcode"));
                coor.put("lastUpdateIp", map.get("ip"));
                coor.put("endDate", DateUtil.nowTime());
                coor.put("lastUpdateDate", DateUtil.nowTime());
                String wmsDeliveryCoordinateId = (String) coor.get("wmsDeliveryCoordinateId");
                if (wmsDeliveryCoordinateId == null || wmsDeliveryCoordinateId.equals("")) {
                    error++;
                } else {
                    Integer result = wmsDeliveryCoordinateDao.searchStatus(wmsDeliveryCoordinateId);
                    if (result == 1) {
                        wmsDeliveryCoordinateDao.updateToZeroWmsDeliveryCo(coor);
                        success++;
                    } else {
                        error++;
                    };
                }
            }
            platformTransactionManager.commit(transaction);
            msg = "成功:"+success+"条，失败："+error+"条。";
        }catch (Exception e){
            platformTransactionManager.rollback(transaction);
            e.printStackTrace();
            return "归零失败";
        }
        return msg;
    }
    //交接单查询
    public QueryRespBean<List<HashMap>> searchDeliverPlan(QueryReqBean<WmsDeliverPlanDTO> queryReqBean) {
        QueryRespBean<List<HashMap>> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            WmsDeliverPlanDTO searchParams = queryReqBean.getSearchParams();
            Page<List<HashMap>> dataList = wmsDeliveryCoordinateDao.searchDeliver(searchParams);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage(), e);
        }
    }
    @Transactional
    //发起协调后向GK网发送信息
    public String sendToGK(String wmsDeliveryCoordinateId, String opUserCode, String userIp, String wmsDeliveryPlanId) {
        HashMap map = wmsDeliveryCoordinateDao.sendMessageToGK(wmsDeliveryCoordinateId);
        map.put("opUserCode", opUserCode);
        map.put("userIp", userIp);
        map.put("wmsCoordinateInfoId", wmsDeliveryCoordinateId);
        map.put("coordinateSort",map.get("coordinateSort"));
        map.put("coordinateDesc",map.get("coordinateDesc"));
        JSONObject data = new JSONObject(map);
        //放入请求头
        JSONObject headersMap = new JSONObject();
        headersMap.put("func", environment.getProperty("deliveryCoordinate.func"));
        String msgId= CreatMsgId.getMsgId();
        headersMap.put("msgId", msgId);
        headersMap.put("data", data);

        String headersmap = headersMap.toJSONString();
        log.info("===========================工控网上传_发起协调===========================");
        //工控网上传数据
        HashMap issuedTest= new HashMap();
        issuedTest.put("BData",headersmap);
        issuedTest.put("msgId", msgId);
        issuedTest.put("type",environment.getProperty("deliveryCoordinate.func"));
        issuedTest.put("businessVal",wmsDeliveryPlanId);
        issuedTest.put("businessCol","wms_delivery_plan_id");
        issuedTest.put("businessTab","wms_delivery_plan");
        log.info("工控网上传程序后台日志:>>>>>>>>>>>>>>>>>>>>>>>>>issuedParameters:"+issuedTest.toString());
        log.info("===========================工控网上传_发起协调===========================");
        workService.issuedTest(issuedTest);
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersmap.getBytes());
        return BData;
    }
    @Transactional
    //查询协调问题类型
    public List<HashMap> searchProblemType(){
        return wmsDeliveryCoordinateDao.searchProblemType();
    }
}
